"use client";

import Link from "next/link";
import Image from "next/image";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";
import { MoreHorizontal } from "lucide-react";
import { Overlay } from "./overlay";
import { Footer } from "./footer";

import { api } from "@/convex/_generated/api";
import { Actions } from "@/components/actions";
import { useAuth } from "@clerk/nextjs";
import { Skeleton } from "@/components/ui/skeleton";
import { useApiMutation } from "@/hooks/use-api-mutaion";
import { toast } from "sonner";

interface BoardCardProps {
  key: string;
  id: string;
  title: string;
  imageUrl: string;
  authorId: string;
  authorName: string;
  createdAt: number;
  orgId: string;
  isFavorites: boolean;
}

/**
 * 会员卡片组件
 */

export const BoardCard = ({
  id,
  title,
  imageUrl,
  authorId,
  authorName,
  createdAt,
  orgId,
  isFavorites,
}: BoardCardProps) => {
  // 返回当前的身份验证状态，用户id等
  const { userId } = useAuth();
  const authorLabel = userId === authorId ? "你得" : authorName;
  const createdAtLabel = formatDistanceToNow(createdAt, {
    addSuffix: true, // 为时间差的结果添加一个后缀，表示该时间是在“之前”还是“之后”
    locale: zhCN,
  });

  const { mutate: onFavorite, pedding: peddingFavorite } = useApiMutation(
    api.board.favorite
  );
  const { mutate: onUnFavorite, pedding: peddingUnPedding } = useApiMutation(
    api.board.unFavorite
  );

  const toggleFavorite = () => {
    if (isFavorites) {
      onUnFavorite({ id }).catch(() => toast.error("取消收藏失败"));
    } else {
      onFavorite({
        id,
        orgId,
      }).catch(() => {
        toast.error("收藏失败");
      });
    }
  };

  return (
    <Link href={`/board/${id}`}>
      <div className="group aspect-[100/167] border rounded-lg flex flex-col justify-between overflow-hidden ">
        <div className="relative flex-1 bg-amber-50 ">
          <Image fill priority src={imageUrl} alt={title} sizes="auto auto" />
          <Overlay />
          <Actions id={id} side="right" title={title}>
            <button className="absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition-opacity px-3 py-2 outline-none">
              <MoreHorizontal className="opacity-75 hover:opacity-100 transition-opacity text-white" />
            </button>
          </Actions>
        </div>
        <Footer
          isFavorites={isFavorites}
          title={title}
          authorLabel={authorLabel}
          createdAtLabel={createdAtLabel}
          onClick={toggleFavorite}
          disabled={peddingFavorite || peddingUnPedding}
        ></Footer>
      </div>
    </Link>
  );
};

BoardCard.Skeleton = function BoardCardSkeletion() {
  return (
    <div className="group aspect-[100/167]  rounded-lg overflow-hidden ">
      <Skeleton className="h-full w-full" />
    </div>
  );
};
